<template>
  <div class="shopcar-container">
    <div class="goods-list">
      <div v-for="(item, i) in cartList" :key="i">
        <div class="card-content">
          <!-- 复选框 -->
          <div class="checkbox">
            <input
              type="checkbox"
              v-model="item.is_checked"
              @change="onCheckedChange(item)"
              :disabled="item.goods_num == 0"
            />
          </div>
          <!-- 中间商品图片 -->
          <img :src="APIBaseURL + item.goods_img" />
          <!-- 右侧部分 -->
          <div class="info">
            <h1>{{ item.goods_name }}</h1>
            <p class="">
              <span class="price">¥{{ item.price }}</span>
              <number
                v-if="item.goods_num"
                @onCountChanged="onCountChanged"
                :initcount="item.count"
                :max="item.goods_num"
                :id="item.id"
              ></number>
              <span v-else style="margin-right: 20px">该商品暂时无货</span>
              <a href="#" @click.prevent="onClickDeleteCartItem(item.id)">删除</a>
            </p>
          </div>
        </div>
      </div>
      <!-- 商品结算区域 -->
      <div class="">
        <div class="card-content">
          <div class="balance">
            <div class="left">
              <p>总计不含运费</p>
              <p>
                已勾选商品
                <span class="red">{{ getCheckedCount }}</span> 件，总价
                <span class="red">¥{{ getCheckedAmount }}</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div>
      <mt-button size="large" @click="onClickCreateOrder">去结算</mt-button>
    </div>
  </div>
</template>

<script>
import Number from "../components/Number.vue";
import {HTTPGetCartList,HTTPUpdateCartCount,HTTPUpdateCartChecked,HTTPDeleteCartItem} from "@/api/cart.js"
export default {
  data() {
    return {
      cartList: [],
    };
  },
  computed: {
    getCheckedCount(){
      let sum = 0;
      this.cartList.forEach((item) => {  
        if(item.is_checked)      
          sum += 1;        
      });
      return sum;
    },
    getCheckedAmount() {      
      let amount = 0;
      this.cartList.forEach((item) => { 
        if(item.is_checked)       
          amount += item.price * item.count;        
      });
      return amount;
    },
  },
  created() {
    this.getCartList();
  },
  methods: {
    async getCartList() {
      try {        
        let result = await HTTPGetCartList();
        // console.log(result)
        if(result.code == 1){          
          this.cartList = result.data; 
          this.cartList.forEach((item) => {
            if (item.goods_num == 0) {
              //如果商品库存数为0，则不能选中
              item.is_checked = false;
              this.onCheckedChange(item.id,item.is_checked);
            }
          });
        }
        else if (result.code == 2) {  //需要用户登录的
          this.$router.push({ name: "login" });
        }
        else {
          throw result.msg;
        }
      } catch (error) {
        this.$messagebox("错误",error)        
      }
    },//===================================================  


    async onCountChanged(goodsinfo) {  //goodsinfo = { id: this.id, count: count }
      let params = goodsinfo;      
      //请求后端更改数据-购物商品数量
      try {
        let result = await HTTPUpdateCartCount(params);
        if(result.code == 1)
        {
          this.getCartList() ;  //重新加载购物车列表
        }
        else
        {
          throw result.msg;
        }
      } catch (error) {
        this.$messagebox("错误",error)
      }      
    },//===================================================  
    async onCheckedChange(item) {
      let id = item.id;
      let is_checked = item.is_checked == true ?  1: 0;

      let params = {id,is_checked} ;
      // console.log(params)
      //请求后端更改数据-购物商品选中状态
      try {
        let result = await HTTPUpdateCartChecked(params);
        if(result.code == 1) 
        {
          this.getCartList()   //重新加载购物车列表
        }
        else{
          throw result.msg;
        }
      } catch (error) {
        this.$messagebox("错误",error)
      } 
    },//===================================================  
    async onClickDeleteCartItem(id) {
      //请求后端更改数据-删除购物商品
      let ids = id;
      try {
        let result = await HTTPDeleteCartItem({ids});
        if(result.code == 1) {this.getCartList()}//重新加载购物车列表
        else {throw result.msg;}
      } catch (error) {
        this.$messagebox("错误",error)
      } 
    },//===================================================
    onClickCreateOrder() {
      if (this.cartList.length === 0) {
        this.$toast("您的购物车为空");
        return;
      }      
      //要确保购物车数据和后端数据库的是一致的 .....
      this.$router.push({ name: "order_create" });
    },
  },
  components: {
    Number,
  },
};
</script>

<style lang="scss" scoped>
.shopcar-container {
  display: flex;
  flex-direction: column;
  background: #eee;
  overflow: hidden;
  .goods-list {
    .card-content {
      display: flex;
      flex-direction: row;
      align-items: center;
      padding: 10px;

      .checkbox {
        padding: 2px;
      }
    }
    img {
      width: 80px;
    }
    .info {
      margin-left: 10px;
      width: 100%;
      overflow: hidden;
      box-sizing: border-box;
      h1 {
        font-size: 13px;
        font-weight: bold;
        line-height: 20px;
        padding-top: 10px;
      }
      p {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        .price {
          text-align: left;
          font-size: 16px;
          font-weight: 700;
          color: red;
          flex: 1;
          padding-right: 5px;
        }
        a {
          line-height: 25px;
        }
      }
    }
  }
  .balance {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    .red {
      color: red;
      font-weight: bold;
      font-size: 16px;
    }
  }
}
</style>
